<template>
  <div class="app-container">
    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <!-- <div class="data-table__toolbar--actions">
          <el-button
            type="danger"
            :disabled="selectedIds.length === 0"
            icon="delete"
            @click="() => handleDelete()"
          >
            删除
          </el-button>
          <el-button type="success" icon="refresh" @click="handleTriggerManual">手动触发</el-button>
          <el-button type="primary" icon="search" @click="handleCheckEvent">检查事件</el-button>
          <el-button type="warning" icon="plus" @click="handleTriggerEvent">触发新事件</el-button>
        </div> -->
        <div class="data-table__toolbar--filters">
          <!-- 分类筛选：全部 / 检修 / 启动 / 故障 -->
          <el-radio-group v-model="reportType" @change="handleReportTypeChange">
            <el-radio-button value="all">全部</el-radio-button>
            <el-radio-button value="检修">检修</el-radio-button>
            <el-radio-button value="启动">启动</el-radio-button>
            <el-radio-button value="故障">故障</el-radio-button>
          </el-radio-group>
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateRangeChange"
          />
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="faultReportList"
        highlight-current-row
        border
        fit
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          v-for="(col, index) in coreColumns"
          :key="index"
          :prop="col.key"
          :label="col.label"
          :min-width="col.width"
          align="left"
          :fixed="col.fixed || false"
        >
          <template #default="{ row }">
            <span>{{ getValueByKey(row, col.key) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="270">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              icon="view"
              @click="() => openDetailDrawer(scope.row)"
            >
              详情
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              icon="view"
              @click="() => goToWaveChart(scope.row)"
            >
              录波
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              icon="download"
              @click="() => handleDownload(scope.row.index)"
            >
              下载
            </el-button>
            <!-- <el-button
              type="danger"
              size="small"
              link
              icon="delete"
              @click="() => handleDelete(scope.row.index)"
            >
              删除
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <offset-pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:offset="queryParams.offset"
        v-model:limit="queryParams.limit"
        @pagination="fetchData"
      />
    </el-card>

    <el-drawer v-model="drawerVisible" title="SOE详情" size="40%" :with-header="true">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="序号">{{ selectedRow?.index }}</el-descriptions-item>
        <el-descriptions-item label="时间">{{ selectedRow?.datetime }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ selectedRow?.type }}</el-descriptions-item>
        <el-descriptions-item label="短语">{{ selectedRow?.phrase }}</el-descriptions-item>
        <el-descriptions-item label="距离">{{ selectedRow?.distance }}</el-descriptions-item>
        <el-descriptions-item label="动作">{{ selectedRow?.action }}</el-descriptions-item>
        <el-descriptions-item label="持续时间">{{ selectedRow?.duration }}</el-descriptions-item>
        <el-descriptions-item label="SOE条目">
          <el-collapse>
            <el-collapse-item v-for="(soe, idx) in selectedRow?.soe" :key="idx">
              <template #title>
                <span class="font-bold">{{ soe.name }}</span>
                <span class="ml-2 text-gray-500">({{ soe.relative_time }})</span>
              </template>
              <el-descriptions :column="2" border v-if="soe.values">
                <el-descriptions-item
                  v-for="(val, vIdx) in soe.values"
                  :key="vIdx"
                  :label="val.name"
                >
                  {{ val.value }} {{ val.unit }}
                </el-descriptions-item>
              </el-descriptions>
            </el-collapse-item>
          </el-collapse>
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useFaultReportStore } from "@/store";
import type { FaultReportItem } from "@/api/hmi/fault-report.api";
import { useRouter } from "vue-router";

defineOptions({
  name: "FaultReport",
  inheritAttrs: false,
});

interface FetchQueryParams {
  offset: number;
  limit: number;
  startTime: string;
  endTime: string;
  reportType: string;
}

const router = useRouter();
const faultReportStore = useFaultReportStore();
// 只保留新API相关状态
const rawFaultReportList = ref<FaultReportItem[]>([]);
const faultReportList = ref<FaultReportItem[]>([]);
const total = ref(0);
const loading = ref(false);
const selectedIds = ref<number[]>([]);
const selectedRow = ref<FaultReportItem | null>(null);

// 只展示新API核心字段
const coreColumns = [
  { key: "fault_file_name", label: "文件名", minWidth: 180, fixed: true },
  { key: "index", label: "序号", width: 120, fixed: true },
  { key: "datetime", label: "时间", width: 220, fixed: true },
  { key: "type", label: "类型", width: 120, fixed: true },
];

// 查询参数
const queryParams = reactive<FetchQueryParams>({
  offset: 0,
  limit: 10,
  startTime: "",
  endTime: "",
  reportType: "all",
});

const reportType = ref("all");
const dateRange = ref<[string, string] | undefined>(undefined);

// 详情抽屉相关
const drawerVisible = ref(false);

function getValueByKey(row: any, key: string) {
  return key.split(".").reduce((obj, k) => obj?.[k], row) ?? "-";
}

function handleSelectionChange(selection: any[]) {
  const ids = selection.map((item: any) => item.index);
  selectedIds.value = ids;
}

/**
 * 受限于API 实现， 仅模拟本地数据删除功能
 * @param rowId 行ID
 */
function handleDelete(rowId?: number) {
  const rowIds = rowId ? [rowId] : selectedIds.value;
  if (!rowIds.length) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  try {
    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        rawFaultReportList.value = rawFaultReportList.value.filter(
          (item) => !rowIds.includes(item.index)
        );
        ElMessage.success("删除成功");
        fetchData();
      })
      .catch(() => {
        ElMessage.info("取消删除");
      });
  } catch (error) {
    ElMessage.error("删除失败");
    console.error("删除失败:", error);
  }
}

/**
 * 受限于API 实现， 仅模拟本地数据下载
 * 实现仅前端的下载功能，下载内容为 当前行数据
 * @param rowId 行ID
 */
function handleDownload(rowId: number) {
  try {
    const row = rawFaultReportList.value.find((item) => item.index === rowId);
    if (row) {
      const data = JSON.stringify(row);
      const blob = new Blob([data], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `fault_report_${rowId}.json`;
      a.click();
      URL.revokeObjectURL(url);
    } else {
      ElMessage.error("数据不存在");
    }
    ElMessage.success(`已下载: fault_report_${rowId}.json`);
  } catch (error) {
    ElMessage.error("下载失败");
    console.error("下载失败:", error);
  }
}

function handleTriggerManual() {
  try {
    // await faultReportStore.triggerGenerate(apiPath.value);
    ElMessage.success("手动触发成功");
    // 重新获取数据
    fetchData();
  } catch (error) {
    ElMessage.error("手动触发失败");
    console.error("手动触发失败:", error);
  }
}

async function handleCheckEvent() {
  try {
    // const result = await faultReportStore.checkEvent(apiPath.value);
    ElMessage.success("检查事件成功");
    // console.log("检查事件结果:", result);
  } catch (error) {
    ElMessage.error("检查事件失败");
    console.error("检查事件失败:", error);
  }
}

async function handleTriggerEvent() {
  try {
    // await faultReportStore.triggerEvent(apiPath.value);
    ElMessage.success("触发新事件成功");
    // 重新获取数据
    await fetchData();
  } catch (error) {
    ElMessage.error("触发新事件失败");
    console.error("触发新事件失败:", error);
  }
}

function handleReportTypeChange() {
  queryParams.reportType = reportType.value;
  // 分类变化后回到第一页
  queryParams.offset = 0;
  fetchData();
}

function goToWaveChart(row: FaultReportItem) {
  // router.push(`/chart/wave-chart`);

  // 带着路由参数 meta.fault_name 传到 wave-chart 路由;
  // row.fault_file_name;
  router.push({
    path: "/chart/backend-wave-chart",
    query: {
      fault_name: row.fault_file_name,
    },
  });
}

function handleDateRangeChange() {
  if (dateRange.value) {
    const [startDate, endDate] = dateRange.value;
    queryParams.startTime = startDate;
    queryParams.endTime = endDate;
  } else {
    queryParams.startTime = "";
    queryParams.endTime = "";
  }
  // 日期变化后回到第一页
  queryParams.offset = 0;
  fetchData();
}

function fetchData() {
  const { offset, limit, startTime, endTime, reportType } = queryParams;
  // 基于内存数据源进行筛选（避免再次请求后端）
  const filteredList = rawFaultReportList.value.filter((item) => {
    const inDate = matchByDate(item.datetime, startTime, endTime);
    if (reportType === "all") return inDate;
    const inType = matchByCategory(item.type, reportType);
    return inDate && inType;
  });
  // console.log(filteredList);
  faultReportList.value = filteredList.slice(offset, offset + limit);
  total.value = filteredList.length;
}

async function fetchRawData() {
  // 这里只做演示，实际应调用新API批量获取接口
  // 假设用mock数据或直接fetch /api/fault/1
  try {
    loading.value = true;
    // 示例：只获取一个
    const result = await faultReportStore.fetchFaultReportByCpuId(1);
    // 排序 index 从小到大
    rawFaultReportList.value = result.sort((a, b) => a.index - b.index);
    loading.value = false;
  } catch {
    loading.value = false;
  }
}

async function openDetailDrawer(row: FaultReportItem) {
  selectedRow.value = row;
  drawerVisible.value = true;
}

onMounted(async () => {
  await fetchRawData();
  fetchData();
});

/**
 * 工具函数：按类型匹配（检修/启动/故障），严格等值比较（去除首尾空格）
 */
function matchByCategory(typeValue: string, category: string): boolean {
  return (typeValue ?? "").trim() === category;
}

/**
 * 工具函数：将时间字符串转换为时间戳
 * 支持：
 *  - 带毫秒：YYYY-MM-DD HH:mm:ss.SSS
 *  - 不带毫秒：YYYY-MM-DD HH:mm:ss（在外部先补 .000/.999 再传入）
 */
function toTs(s: string): number {
  return new Date(s.replace(" ", "T")).getTime();
}

/** 补齐开始时间的毫秒为 .000 */
function ensureMsStart(s: string): string {
  if (!s) return s;
  return /\.\d{1,3}$/.test(s) ? s : `${s}.000`;
}
/** 补齐结束时间的毫秒为 .999（包含边界） */
function ensureMsEnd(s: string): string {
  if (!s) return s;
  return /\.\d{1,3}$/.test(s) ? s : `${s}.999`;
}

/**
 * 工具函数：按日期范围匹配
 * rowDatetime: YYYY-MM-DD HH:mm:ss.SSS
 * start/end:   DatePicker 返回 YYYY-MM-DD HH:mm:ss（无毫秒）
 */
function matchByDate(rowDatetime: string, start: string, end: string): boolean {
  if (!start && !end) return true;
  const t = toTs(rowDatetime);
  if (start && end) {
    const sTs = toTs(ensureMsStart(start));
    const eTs = toTs(ensureMsEnd(end));
    return t >= sTs && t <= eTs;
  }
  if (start && !end) {
    const sTs = toTs(ensureMsStart(start));
    return t >= sTs;
  }
  if (!start && end) {
    const eTs = toTs(ensureMsEnd(end));
    return t <= eTs;
  }
  return true;
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 24px;
}

.data-table__toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
  gap: 12px;
}

.data-table__toolbar--actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.data-table__toolbar--filters {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.data-table__content {
  min-width: 700px;
  margin-bottom: 16px;
}

.font-bold {
  font-weight: bold;
}

.ml-2 {
  margin-left: 0.5rem;
}

.text-gray-500 {
  color: #6b7280;
}
</style>
